﻿//  --------------------------------
//  Copyright (c) 2010 Michael Schuler, Sascha Burger. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://p2pmessaging.codeplex.com/license
//  ---------------------------------
using System;
using LoungeRepo.Core;
using p2pMessaging.Interfaces;

namespace p2pMessaging.BL
{
    /// <summary>
    /// The LoungeRepositoryPersistenceService is responsible for store, get, delete on the LoungeRepo
    /// </summary>
	public sealed class LoungeRepositoryPersistenceService : IPersistenceService
	{
		/// <summary>
		/// Store an instance of <see cref="T"/> to the repository.
		/// </summary>
		/// <typeparam name="T">Type of <see cref="IPersistenceEntity"/></typeparam>
		/// <param name="t">Instance of <see cref="T"/>.</param>
		public void Store<T>(T t) where T : IPersistenceEntity
		{
			using (var repo = new LoungeRepository())
			{
				repo.Store(t);
			}
		}

		/// <summary>
		/// Remove an instance of <see cref="T"/> from the repository.
		/// </summary>
		/// <typeparam name="T">Type of <see cref="IPersistenceEntity"/></typeparam>
		/// <param name="t">Instance of <see cref="T"/>.</param>
		public void Delete<T>(T t) where T : IPersistenceEntity
		{
			using (var repo = new LoungeRepository())
			{
				repo.Delete(t.Id);
			}
		}

		/// <summary>
		/// Gets a specific instance of <see cref="T"/> from the repository by its unique id.
		/// </summary>
		/// <typeparam name="T">Type of <see cref="IPersistenceEntity"/></typeparam>
		/// <param name="id">Unique id of the instance.</param>
		/// <returns>Instace of <see cref="T"/> if found otherwise null.</returns>
		public T Get<T>(string id) where T : IPersistenceEntity
		{
			try
			{
				using (var repo = new LoungeRepository())
				{
					return repo.Load<T>(id);
				}
			}
			catch (Exception)
			{
				return default(T);
			}
		}
	}
}
